package yxy.game.pm2.command.infinite;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.module.RedisLock;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.InfiniteMessage;
import yxy.game.pm2.module.infinite.InfiniteHandle;
import yxy.game.pm2.module.infinite.InfiniteModule;

/** 神将试炼 神将试炼战斗请求 */
@MessageType(proto = Command.InfiniteChanllenge, classtype = InfiniteMessage.InfiniteChanllengeRequest.class)
public class CMD_InfiniteChanllenge extends Command<InfiniteMessage.InfiniteChanllengeRequest> {

	@Override
	public void execute(MessageSource messageSource, InfiniteMessage.InfiniteChanllengeRequest request) {
		String playerCode = messageSource.getTag();

		InfiniteMessage.InfiniteChanllengeResponse.Builder response = InfiniteMessage.InfiniteChanllengeResponse.newBuilder();

		RedisLock lock = InfiniteModule.lock(playerCode);
		try {
			if (lock.tryLock()) {
				InfiniteModule infiniteModule = InfiniteModule.get(playerCode);
				if (infiniteModule == null) {
					send(messageSource, response, Result.ModuleNotOpen);// 模块没开启
					return;
				}

				if (infiniteModule.isBattling()) {
					send(messageSource, response, Result.BattleIsRunning);// 之前的战斗未结束
					return;
				}
				InfiniteHandle handle = new InfiniteHandle();

				int stage = infiniteModule.startStage();

				response.setBattle(handle.battleResponse(playerCode, stage));
				send(messageSource, response, Result.Success);
			}
		} catch (Exception e) {
			e.printStackTrace();
			send(messageSource, response, Result.DataError);
		} finally {
			lock.unlock();
		}
	}

	private void send(MessageSource messageSource, InfiniteMessage.InfiniteChanllengeResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}